package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

/**
 * @ClassName CacheClient
 * @Description TODO
 * @Author guobenqi
 * @Date 2022/4/23 10:06
 */
@Component
@Slf4j
public class CacheClient {
    private StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void set(String key, Object value, Long time, TimeUnit timeUnit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,timeUnit);
    }
    //设置逻辑过期时间
    public void setWithLogicalExpire(String key,Object value,Long time,TimeUnit unit){
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        //写入redis
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(redisData));
    }
    //缓存穿透 的方案
    public <R,Id> R queryWithPassThrough(String keyPrefix, Id id, Class<R> type, Function<Id,R> dbFallBack,
                                         Long time,TimeUnit unit
    ){
        String key = keyPrefix + id;
        //从redis查询缓存
        String  json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(json)) {
           return JSONUtil.toBean(json,type);
        }
        if (json != null){
            return null;
        }
        //判断存在
        //不存在查询数据库
        R r = dbFallBack.apply(id);
        if (r == null){
            //将空值写入redis
            stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }


        this.set(key,r,time,unit);
        //存在，写入redis
        return r;
    }

    private boolean tryLock(String key){
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(aBoolean);
    }
    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }
    /*线程池*/
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    //缓存击穿的key不过其
    public <R,Id> R queryWithLogicalExpire(String keyPrefix, Id id,Class<R> type,Function<Id,R> dbFallBack, Long time,TimeUnit unit){
        String key = keyPrefix + id;
        //从redis查询缓存
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(json)) {
            return  null;
        }
        //命中,反序列化
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();
        //判断是过期
        if (expireTime.isAfter(LocalDateTime.now())) {
//            System.out.println("你好");
            return r;
        }
        //实现缓存重建
//        获取互斥锁

        String lockKey = LOCK_SHOP_KEY+id;
        boolean isLock = tryLock(lockKey);
        if (isLock){
            //开启独立线程去缓存重建
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    //重建缓存
                    //差数据库
                    R r1 = dbFallBack.apply(id);
                    //保存redis
                    this.setWithLogicalExpire(key,r1,time,unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    //释放锁
                    unlock(lockKey);
                }

            });
        }
        return r;
    }
}
